import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/login/Login.vue'
import Register from '../components/login/Register.vue'  
import Home from '../components/home/index.vue'
import Welcome from '../components/welcome/index.vue'
import Menu from '../components/menu/Menu.vue'
import Swagger from '../components/swagger/index.vue'
import User from '../components/user/Users.vue'
import Druid from '../components/druid/index.vue'
Vue.use(VueRouter)

const routes = [
  {
        path: '/',
        redirect: '/login'
    },
    {
        path: '/login',
        component: Login
    },    
    { 
      path: '/register',     
      component: Register
    },
    {
        path: '/home',
        component: Home,
        redirect: '/welcome',
        children: [{
                path: '/welcome',
                component: Welcome
            },
            {
                path: '/pages/menu/menuList',
                component: Menu
            },
            {
                path: '/swagger-ui',
                component: Swagger
            },
            {
                path: '/sys/user/query',
                component: User
            },
            {
                path: '/druid/index',
                component: Druid
            }
        ]
    } 
]

const router = new VueRouter({
    mode: 'history',
    routes
})

// 挂载导航守卫

router.beforeEach((to, from, next) => {
    // to 将要访问的路径
    // from 代表从哪个路径跳转而来
    // next 是一个函数 ，表示放行
    if (to.path === '/login' || to.path === '/register'){
        next() // 直接跳转
    }
    else{  //判断是否存在token
         // 获取token
        const tokenStr = window.sessionStorage.getItem('token')
        if (!tokenStr){  //不存在
            return next('/login')
        } 
        next()
    }    
})

export default router
